package Servlet;

import CookieUtil.CookieUtil;
import Service.ManagerService;
import model.Manager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cyt
 * @date 2020/8/8
 */

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        for (Cookie c : cookies){
            if(c.getName().equals("token") && c.getValue().equals(Manager.getToken())){
                System.out.println("找到cookie啦！！"+c.getName()+c.getValue());
                req.getSession().setAttribute("manager",new Manager("admin","123456"));
                RequestDispatcher requestDispatcher = req.getRequestDispatcher("/studentPageQueryServlet");
                requestDispatcher.forward(req, resp);
                return;
            }
        }
        String username = req.getParameter("username");
        System.out.println("获取到的用户名为:"+username);
        String password = req.getParameter("password");
        System.out.println("密码是:"+password);
        ManagerService managerService = new ManagerService();
        Manager manager = managerService.managerLogin(new Manager(username, password));
        if(manager == null){
            req.setAttribute("error","登陆失败，用户名或者密码错误！");
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(req,resp);
        }else {
            CookieUtil cookieUtil = new CookieUtil();

            Cookie cookie = new Cookie("token", Manager.getToken());
            cookie.setMaxAge(604800);
            resp.addCookie(cookie);
            System.out.println("成功加入cookie!!");
            req.getSession().setAttribute("manager",manager);
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/studentPageQueryServlet");
            requestDispatcher.forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
